﻿-- Function: nearest_stops(text, text)

-- DROP FUNCTION nearest_stops(text, text);

CREATE OR REPLACE FUNCTION nearest_stops(latitude text, longitude text)
  RETURNS SETOF londonbusstops AS
$BODY$
DECLARE point text;
	sql text;
BEGIN

point = '''POINT(' || longitude || ' ' || latitude || ')''';

sql = 'SELECT * FROM londonbusstops ' ||
	'WHERE ST_DWithin(wkb_geometry,ST_GeomFromText(' || point || ',4326),0.05)' ||
	'ORDER BY ST_Distance(wkb_geometry,ST_GeomFromText(' || point || ',4326)) ASC LIMIT 10';

RETURN QUERY EXECUTE sql;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;
ALTER FUNCTION nearest_stops(text, text) OWNER TO postgres;
